<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/5
 * Time: 9:51
 */

namespace app\admin\controller;

use app\admin\model\Staff as StaffModel;
use app\admin\model\Role as RoleModel;
use think\Request;
use think\Collection;
use think\Db;

class StaffController extends  BaseController
{
    public function lst()
    {
        $params = $this->request->param();
        if(!empty($params['name'])){
            $name = "%".$params['name']."%";
        }else{
            $name = "%%";
        }
        $data = StaffModel::where('name','like',$name)
            ->order('id','asc')
            ->paginate(6, false, [
                'query' => request()->param(),
            ]);
        $page = $data->render();
        $this->assign([
            'page' => $page,
            'data' => $data,
        ]);
        return $this->fetch();
    }

    public function add()
    {
        $request = Request::instance();
        switch  ($request->method()){
            case "GET":
                return $this->fetch();
                break;
            case "POST":
                $params = $request->param();
                $controller = strtolower($request->controller());
                if(request()->file('pic')){
                    $picInfo = uploadOne($controller,'thumb','pic',80,80);
                    $params['pic'] = $picInfo['pic'];
                    $params['sm_pic'] = $picInfo['thumb_pic'];
                }
                $model = new StaffModel();
                if($model->validate('StaffValidate')->allowField(true)->save($params)){
                    $this->success('添加管理员成功!',url('admin/staff/lst'),'',1);
                    exit;
                }
                else{
                    $this->error($model->getError());
                    exit;
                }
                break;
            default:
                return "错误的数据信息";
        }
    }

    public function edi()
    {
        $request = Request::instance();
        switch  ($request->method()){
            case "GET":
                $id = $request->param('id');
                $this->assign('data',StaffModel::find($id));
                return $this->fetch();
                break;
            case "POST":
                $params = $request->param();
                if($params['id'] == 1){
                    if((!empty($params['name'])) && ($params['name'] !== 'admin') ){
                        $this->error('该账户用户名不能被修改');
                    }
                    if((!empty($params['status'])) && ($params['status'] == 2) ){
                        $this->error('该账户状态不能被修改');
                    }
                }
                $model = new StaffModel();
                if(request()->file('pic')){
                    $oldPic = $model->where('id','eq',$params['id'])->find();
                    if(is_file($oldPic['pic'])){
                        unlink($oldPic['pic']);
                    }
                    if(is_file($oldPic['sm_pic'])){
                        unlink($oldPic['sm_pic']);
                    }
                    $controller = strtolower($request->controller());
                    $picInfo = uploadOne($controller,'thumb','pic',80,80);
                    $params['pic'] = $picInfo['pic'];
                    $params['sm_pic'] = $picInfo['thumb_pic'];
                }

                if($model->validate('NodeValidate')->allowField(true)->isUpdate(true)->save($params)){
                    $this->success('修改管理员信息成功!',url('admin/staff/lst'),'',1);
                    exit;
                }
                else{
                    $this->error($model->getError());
                    exit;
                }
                break;
            default:
                return "错误的数据信息";
        }
    }

    public function del()
    {
        $id = $this->request->param("id");
        $staffInfo = StaffModel::find($id);
        if(is_file($staffInfo->pic)){
            unlink($staffInfo->pic);
        }
        if(is_file($staffInfo->sm_pic)){
            unlink($staffInfo->sm_pic);
        }
        if(StaffModel::destroy($id)){
            return true;
        }
        return false;
    }

    public function showRole()
    {
        $params = $this->request->param();
        $roleAll = (new Collection(RoleModel::all()))->toArray();
        $staffInfo = StaffModel::get($params['id']);
        $staffRole = (new Collection($staffInfo->roles))->toArray();

        foreach($roleAll as $k=>$v){
            foreach($staffRole as $key=>$val){
                if($v['id'] == $val['id']){
                    $roleAll[$k] = $staffRole[$key];
                }
            }
        }
        $this->assign([
            'role' => $roleAll,
            'staffId' => $params['id'],
        ]);
        return $this->fetch();
    }

    public function bindRole()
    {
        $params = $this->request->param();
        if(empty($params['staff_id'])){
            $this->error('绑定节点所需的参数错误!');
        }
        Db::table('staff_role')->where('staff_id','eq',$params['staff_id'])->delete();
        if(empty($params['role_id'])){
            $this->success('管理员绑定角色成功',url('admin/staff/lst'),'',1);
        }
        $addRoleList = array_values($params['role_id']);
        $staffInfo = StaffModel::get($params['staff_id']);
        $res = $staffInfo->roles()->saveAll($addRoleList);
        if($res){
            $this->success('管理员绑定角色成功',url('admin/staff/lst'),'',1);
        }
        else{
            $this->error('管理员绑定角色失败');
        }
    }

    public function showEditPass()
    {
        $params = $this->request->param();
        if($this->request->isGet()){
            $staff = Db::table('staff')->where(['id'=>$params['id']])->find();
            $this->assign([
                'staff'=>$staff,
            ]);
            return $this->fetch();
        }
        if($this->request->isPost()){
            $staff = Db::table('staff')->where(['id'=>$params['id']])->find();
            $oldPass = md5($params['old_pass']);
            $check = Db::table('staff')->where(['name'=>$staff['name'],'password'=>$oldPass])->find();
            if(!$check){
                $this->error('管理员密码错误');
            }else{
                if(Db::table('staff')->where(['id'=>$params['id']])->update(['password'=>md5($params['new_pass'])])){
                    $this->success('管理员密码修改成功!',url('admin/staff/lst'),'',1);
                }else{
                    $this->error('新密码更新失败');
                }
            }

        }
    }

}